<?php
// 启用错误显示 (生产环境建议关闭)
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

// 设置无限执行时间
set_time_limit(0);

// 引入 Composer 自动加载
$autoloadPath = __DIR__ . '/../vendor/autoload.php';
if (!file_exists($autoloadPath)) {
    header('Content-Type: application/json; charset=utf-8');
    http_response_code(500);
    echo json_encode(['error' => true, 'message' => 'Composer autoload file not found. Please run composer install.']);
    exit;
}
require $autoloadPath;

try {
    // 设置响应头
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');

    // 确保PHP内部使用UTF-8编码
    if (function_exists('mb_internal_encoding')) {
        mb_internal_encoding('UTF-8');
    }
    if (function_exists('mb_http_output')) {
        mb_http_output('UTF-8');
    }

    // 设置Doctrine Annotations为注释读取器
    if (class_exists('\Doctrine\Common\Annotations\AnnotationReader')) {
        \Doctrine\Common\Annotations\AnnotationReader::addGlobalIgnoredName('mixin');
    }

    // 定义扫描路径
    $scanPaths = [
        __DIR__ . '/../app/controller',
        __DIR__ . '/../app/model', // 扫描模型可能包含的Schema定义
        __DIR__ . '/../app/schema'  // 扫描独立的Schema定义
    ];

    // 添加虚拟注解文件，确保Info注解始终存在
    $virtualApiFile = sys_get_temp_dir() . '/virtual_api_info_' . md5(__DIR__) . '.php';
    $virtualInfoContent = '<?php
    /**
     * @OA\Info(
     *     title="纸条盲盒系统 API (Generated)",
     *     version="1.0.0",
     *     description="纸条盲盒系统接口文档"
     * )
     */
    final class VirtualApiInfo {}
    ';
    file_put_contents($virtualApiFile, $virtualInfoContent);
    $scanPaths[] = $virtualApiFile;

    // 使用Swagger自动扫描
    if (!class_exists('\OpenApi\Generator')) {
         throw new Exception('OpenApi Generator class not found. Is swagger-php installed correctly?');
    }

    $openapi = \OpenApi\Generator::scan($scanPaths, ['validate' => false]);

    // 手动确保基础信息存在
    if (!isset($openapi->info) || !$openapi->info instanceof \OpenApi\Annotations\Info) {
        $openapi->info = new \OpenApi\Annotations\Info([
             'title' => '纸条盲盒系统 API (Fallback)',
             'version' => '1.0.0',
             'description' => '纸条盲盒系统接口文档 (Fallback Info)'
        ]);
    }

    // 确保服务器信息存在
    if (!isset($openapi->servers) || empty($openapi->servers)) {
         $openapi->servers = [
             new \OpenApi\Annotations\Server(['url' => 'http://api-mh.com', 'description' => '测试环境'])
         ];
    }

    // 确保组件和安全方案存在
    if (!isset($openapi->components) || !$openapi->components instanceof \OpenApi\Annotations\Components) {
        $openapi->components = new \OpenApi\Annotations\Components([]);
    }
    if (!isset($openapi->components->securitySchemes) || !is_array($openapi->components->securitySchemes)) {
        $openapi->components->securitySchemes = [];
    }

    // 添加默认的 BearerAuth 安全方案（如果不存在）
    $hasBearerAuth = false;
    foreach ($openapi->components->securitySchemes as $name => $scheme) {
        if ($name === 'bearerAuth') {
            $hasBearerAuth = true;
            break;
        }
    }
    if (!$hasBearerAuth) {
        $openapi->components->securitySchemes['bearerAuth'] = new \OpenApi\Annotations\SecurityScheme([
            'securityScheme' => 'bearerAuth', // 必须设置这个属性
            'type' => 'http',
            'scheme' => 'bearer',
            'bearerFormat' => 'JWT',
            'description' => '请输入您的Bearer Token'
        ]);
    }

    // 确保全局安全设置（如果需要，并且没有被注解覆盖）
    if (!isset($openapi->security) || empty($openapi->security)) {
        $openapi->security = [['bearerAuth' => []]];
    }

    // 输出JSON
    echo $openapi->toJson(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

    // 清理临时文件
    @unlink($virtualApiFile);

} catch (\Throwable $e) { // 捕获所有错误和异常
    // 设置500状态码
    if (!headers_sent()) {
        header('Content-Type: application/json; charset=utf-8');
        http_response_code(500);
    }

    // 记录错误到日志
    error_log("Swagger-PHP generation error: " . $e->getMessage() . " in " . $e->getFile() . " line " . $e->getLine());

    // 输出详细错误信息 (生产环境应考虑移除详细信息)
    echo json_encode([
        'error' => true,
        'message' => 'Error generating Swagger documentation: ' . $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => $e->getTraceAsString() // 生产环境可以注释掉这行
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
} 